package server;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbcp.BasicDataSource;

import exceptions.LogsStoreException;

public class DBLogWriter implements LogWriter{
	private Connection conn;
	private static BasicDataSource ds = new BasicDataSource();
	
	static{
		ds.setUrl("jdbc:oracle:thin:@172.16.1.230:1521:tarena");
		ds.setDriverClassName("oracle.jdbc.driver.OracleDriver");
		ds.setUsername("scott");
		ds.setPassword("tiger");
		
		ds.setInitialSize(2);
		ds.setMaxActive(5);
		ds.setMaxIdle(2);
		ds.setMaxWait(5*60*1000);
		ds.setValidationQuery("select sysdate from dual");
	}

	public void writeLog(String labip, List<String> data) throws LogsStoreException {
		try {
			conn = ds.getConnection();
			String sql= "insert into heantai_datamingxi (logname,labip," +
			"logintime,logouttime,durations,logip)" +	" values(?,?,?,?,?,?)";
			PreparedStatement pst= conn.prepareStatement(sql);
			conn.setAutoCommit(false);
			
			int count=0;
			for (String s : data) {
				String[] arr = s.split(",");
				pst.setString(1, arr[0]);
				pst.setString(2, arr[1]);
				pst.setLong(3, Long.parseLong(arr[2]));
				pst.setLong(4, Long.parseLong(arr[3]));
				pst.setLong(5, Long.parseLong(arr[4]));
				pst.setString(6, arr[5]);
				pst.addBatch();
				++count;
				if(count%10==0)
					pst.executeBatch();
			}
			pst.executeBatch();
			conn.commit();
			pst.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
				throw new LogsStoreException(e);
			}
			throw new LogsStoreException(e);
		}
		
	}
	
}
